import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class MyServer {
    public static void main(String[] args) throws IOException {
        // try-with-resources
        try (ServerSocket ss = new ServerSocket(8080)) {
            System.out.println("服务器启动...");
            while (true) {
                Socket sock = ss.accept();
                System.out.println("接收到客户端链接：" + sock.getRemoteSocketAddress());
                Thread myThread = new MyHandler(sock);
                myThread.start();
            }
        }
    }
}

class MyHandler extends Thread {
    Socket sock;

    public MyHandler(Socket sock) {
        this.sock = sock;
    }

    public void run() {
        try (InputStream input = this.sock.getInputStream()) {
            try (OutputStream output = this.sock.getOutputStream()) {
                handle(input, output);
            }
        } catch (Exception e) {
            try {
                this.sock.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            e.printStackTrace();
            System.out.println("client disconnected.");
        }
    }

    private void handle(InputStream input, OutputStream output) throws IOException,SQLException{
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
        boolean requestOk = false;
        String first = reader.readLine();
        if (first.equals("GET / HTTP/1.1") || first.equals("GET /style.css HTTP/1.1")) {
            requestOk = true;
        }
        for (; ; ) {
            String header = reader.readLine();
            if (header.isEmpty()) { // 读取到空行时, HTTP Header 读取完毕
                break;
            }
            if (header.equals("sec-ch-ua-platform: \"windows\"")) {
                System.out.println("===" + header);
                requestOk = false;
                break;
            }
            System.out.println(header);
        }
        System.out.println(requestOk ? "Response OK" : "Response Error");
        if (!requestOk) {
            // 发送错误响应:
            writer.write("HTTP/1.0 404 Not Found\r\n");
            writer.write("Content-Length: 0\r\n");
            writer.write("\r\n");
            writer.flush();
        } else {
            String resource = first.split(" ")[1];
            switch (resource) {
                case "/":
                    List<CustomResult> articles = new ArrayList<>();
                    // 从数据库获取真实数据
                    // 参考之前的代码
                    Statement statement = MyDBUtil.getConnection().createStatement();
                    ResultSet rs = statement.executeQuery("select title, url, created_at, updated_at from article");
                    while (rs.next()) {
                        String title = rs.getString("title");
                        String url = rs.getString("url");
                        String createdAt = rs.getString("created_at");
                        String updatedAt = rs.getString("updated_at");
                        CustomResult article = new CustomResult(title, url, createdAt, updatedAt);
                        articles.add(article);
                    }


                    String trs = "";

                    for (int i = 0; i < articles.size(); i++) {
                        CustomResult article = articles.get(i);
                        String tr = """
                    <tr>
                        <th><a href="%s">%s</a></th>
                        <th>%s</th>
                        <th>%s</th>                       
                    </tr>
                    """.formatted(article.getUrl(), article.getTitle(), article.getCreatedAt(), article.getUpdatedAt());

                         trs += tr;
                        }
            // 要返回的 HTML
            String body = """
                    <!DOCTYPE html>
                    <html lang="en">
                                        <head>
                                            <meta charset="UTF-8">
                                            <meta name="viewport" content="width=device-width, initial-scale=1">
                                            <title>hw -v3</title>
                                            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
                                           <link href="style.css" rel="stylesheet">
                                        </head>
                                        <body>
                                        <div class="container">
                                            <nav class="navbar navbar-expand-lg bg-body-tertiary">
                                                <div class="container-fluid">
                                                    <a class="navbar-brand" href="#">Navbar</a>
                                                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                                                        <span class="navbar-toggler-icon"></span>
                                                    </button>
                                                    <div class="collapse navbar-collapse" id="navbarSupportedContent">
                                                        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                                                            <li class="nav-item">
                                                                <a class="nav-link active" aria-current="page" href="#">Home</a>
                                                            </li>
                                                            <li class="nav-item">
                                                                <a class="nav-link" href="#">Link</a>
                                                            </li>
                                                            <li class="nav-item dropdown">
                                                                <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                                    Dropdown
                                                                </a>
                                                                <ul class="dropdown-menu">
                                                                    <li><a class="dropdown-item" href="#">Action</a></li>
                                                                    <li><a class="dropdown-item" href="#">Another action</a></li>
                                                                    <li><hr class="dropdown-divider"></li>
                                                                    <li><a class="dropdown-item" href="#">Something else here</a></li>
                                                                </ul>
                                                            </li>
                                                            <li class="nav-item">
                                                                <a class="nav-link disabled" aria-disabled="true">Disabled</a>
                                                            </li>
                                                        </ul>
                                                        <form class="d-flex" role="search">
                                                            <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
                                                            <button class="btn btn-outline-success" type="submit">Search</button>
                                                        </form>
                                                    </div>
                                                </div>
                                            </nav>
                                                           \s
                                            <table class="table table-hover table-bordered mt-3">
                                                <tr>
                                                    <th>标题</th>
                                                    <th>创建时间</th>
                                                    <th>更新时间</th>
                                                </tr>
                                    """
                                        +
                                        trs
                                        +
                                            """                            
                                            </table>
                                        </div>
                                                           \s
                                        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
                                        </body>
                                        </html>
                    """;
                    // 发送成功响应:
                    writer.write("HTTP/1.1 200 OK\r\n");
                    writer.write("Connection: keep-alive\r\n");
                    writer.write("Content-Type: text/html\r\n");
                    writer.write("Content-Length: " + body.length() + "\r\n");
                    writer.write("\r\n"); // 空行标识Header和Body的分隔
                    writer.write(body);
                    writer.flush();
                    break;
                case "/style.css":
                    String css = """
                            table {
                                /*test*/
                                /*margin-top: 16px;*/
                            }
                            """;
                    writer.write("HTTP/1.1 200 OK\r\n");
                    writer.write("Connection: keep-alive\r\n");
                    writer.write("Content-Type: text/html\r\n");
                    writer.write("Content-Length: " + css.length() + "\r\n");
                    writer.write("\r\n"); // 空行标识Header和Body的分隔
                    writer.write(css);
                    writer.flush();
                    break;
            }
        }

        System.out.println("=== === ===");
    }
}